package gui

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"github.com/sirupsen/logrus"
	"strconv"
	"treesize/src/org/ligson/treesize/util"
)

type ListItemLabel struct {
	widget.Label
	Suffix   string
	Count    int
	FileSize int64
	Files    []*util.MyFileInfo
}

func NewListItemLabel(text string) *ListItemLabel {
	listItemLabel := &ListItemLabel{}
	listItemLabel.SetText(text)
	listItemLabel.ExtendBaseWidget(listItemLabel)
	return listItemLabel
}

func (ltl *ListItemLabel) UpdateText(suffix string, files []*util.MyFileInfo) {
	ltl.Suffix = suffix
	ltl.Count = len(files)
	var size int64 = 0
	for _, file := range files {
		size += file.Size
	}
	ltl.FileSize = size
	ltl.Files = files
	ltl.SetText("文件类型[" + suffix + "]共" + strconv.Itoa(ltl.Count) + "个，占用存储:" + util.FormatBytes(size))
}

func showListContextMenu(tl *ListItemLabel, e *fyne.PointEvent, w fyne.Window) {
	logrus.Info(tl.Text)

	//1 export,2 move 3 del
	var operation int = 1
	dlg := dialog.NewFolderOpen(func(uri fyne.ListableURI, err error) {
		if err != nil {
			logrus.Error(err.Error())
			return
		}
		if uri != nil {
			for _, file := range tl.Files {
				util.FileCopy(file.Path, uri.Path())
			}
			if operation == 1 {
				//export
				dialog.NewInformation("提示", "导出完成", w).Show()
			} else if operation == 2 {
				//move
				for _, file := range tl.Files {
					util.DeleteFile(file.Path)
				}
				dialog.NewInformation("提示", "移动完成", w).Show()
			}

		}
	}, w)
	exportItem := fyne.NewMenuItem("导出", func() {
		operation = 1
		dlg.Show()
	})

	moveItem := fyne.NewMenuItem("移动", func() {
		operation = 2
		dlg.Show()

		loadData(dirLabel.Text, myFileTree)
	})

	delItem := fyne.NewMenuItem("删除", func() {
		operation = 3
		for _, file := range tl.Files {
			util.DeleteFile(file.Path)
		}
		dialog.NewInformation("提示", "删除完成", w).Show()
		loadData(dirLabel.Text, myFileTree)
	})

	menu := fyne.NewMenu("", exportItem, moveItem, delItem)
	widget.ShowPopUpMenuAtPosition(menu, w.Canvas(), e.AbsolutePosition)
}

// TappedSecondary func (m *externWiget) TappedSecondary(e *fyne.PointEvent) {}//右键点击
func (ltl *ListItemLabel) TappedSecondary(e *fyne.PointEvent) {
	showListContextMenu(ltl, e, w)
}
